// pages/discovery/articleDetail/index.js
const common = require('../../../../public.js')
const config = require('../../../../config')
Page({

    data: {
        articleId: '',
        articleDetail: {},
        commentList: [],
        focusList: [],
        commentValue: '',
        pubUserId: '',
        commentId: '',
        commentPlachold: '我来说几句',
        textareaForce: false,
        userInfo: null,
        isLoadingBusy: false,
        title: null,
        storeName: null,
        createTime: 0,
        storeImg: null
    },

    onLoad: function (options) {
        let that = this
        this.data.articleId = options.id
        const title = options.title
        this.setData({
            storeName: options.storeName,
            title,
            createTime: parseInt(options.createTime),
            storeImg: options.storeImg
        })

        wx.setNavigationBarTitle({
            title
        })

        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    userInfo: data.user,
                    token: data.token,
                }, function () {
                    that.getFocusList()
                    that.getArticleDetail()
                    that.getCommentList()
                })
            } else {
                that.getArticleDetail()
                that.getCommentList()
            }
        })
    },
    cancleCommentPraise(id) {
        let that = this
        let tempJson = {
            userId: (that.data.userInfo && that.data.userInfo.id) ? that.data.userInfo.id : '',
            token: that.data.token,
            commentId: id
        }
        common.post('/storeArticle/cancleStoreArticleCommentPraise', tempJson, function (res) {
            if (res.status === 200) {
                that.getCommentList()
            }
        })
    },
    commitPraise(id) { // 点赞
        const that = this
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            commentId: id
        }
        common.post('/storeArticle/saveStoreArticleCommentPraise', tempJson, function (res) {
            if (res.status == 200) {
                that.getCommentList()
            }
        })
    },
    praiseAction(e) {
        const id = e.currentTarget.dataset.item.id
        const userPraiseFlag = e.currentTarget.dataset.item.userPraiseFlag
        if (userPraiseFlag) {
            this.cancleCommentPraise(id)
        } else {
            this.commitPraise(id)
        }
    },
    onChange(e) {
        let {
            value
        } = e.detail

        this.setData({
            commentValue: value
        })
    },
    getArticleDetail() {
        this.setData({
            isLoadingBusy: true
        })
        const that = this
        const tempJson = {
            userId: (that.data.userInfo && that.data.userInfo.id) ? that.data.userInfo.id : '',
            token: that.data.token ? that.data.token : '',
            articleId: that.data.articleId
        }
        common.post("/storeArticle/getStoreArticleDetail", tempJson, function (res) {
            if (res.status === 200) {
                var jsonDa = JSON.stringify(res.data.content).replace(/<img/gi, "<img class='richImg'style='width:auto!important;height:auto!important;max-height:100%;width:100%;'")
                    .replace(/<div/gi, "<div class='divClass'")
                    .replace(/<span/gi, "<span class='spanClass'")
                // jsonDa = '<div class="div_class">'+jsonDa+'</div>'
                that.setData({
                    articleDetail: res.data,
                    articleContent: JSON.parse(jsonDa),
                    storeName: res.data.storeName,
                    title: res.data.title,
                    createTime: parseInt(res.data.createTime),
                    storeImg: res.data.storeImg
                })
            } else {
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                isLoadingBusy: false
            })
        })
    },
    toBuy(e) {
        let {
            item
        } = e.currentTarget.dataset
        let url = null
        switch (this.data.articleDetail.itemType) {
            //1普通商品 2零元购 3团购商品 4惠特汇商品 5店铺活动 6抽奖
            case 1: // 1普通商品
                common.gotoGoodsPage(item)
                break;
            case 2: // 2零元购 
                url = '/packageC/pages/Zero/Des/index?id=' + item.id + '&name=' + item.title
                break;
            case 3: // 3团购商品
                url = '/pages/crowd/index/index?id=' + item.id
                break;
            case 4: // 4惠特汇商品 
                common.gotoGoodsPage(item, '&isVip=true')
                break;
            case 5: // 5店铺活动
                url = '/pages/Activity/actDes/index?id=' + item.id + '&name=' + item.title + '&isVip=true'
                break;
            case 6: // 6抽奖
                url = '/pages/draw/index?drawId=' + item.id
                break;
            default:
                break;
        }
        if (url) {
            wx.navigateTo({
                url: url
            })
        }
    },
    getCommentList() {
        const that = this
        const tempJson = {
            articleId: that.data.articleId,
            userId: (that.data.userInfo && that.data.userInfo.id) ? that.data.userInfo.id : '',
            token: that.data.token ? that.data.token : '',
            pageNum: 1,
            pageSize: '',
        }
        common.post("/storeArticle/getStoreArticleCommentList", tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    commentList: res.data
                })
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    getFocusList() {
        let that = this
        let tempJson = {
            articleId: that.data.articleId,
            pageNum: 1,
            pageSize: 10,
        }
        common.post("/storeArticle/getStoreArticleFocusList", tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    focusList: res.data
                })
            }
        })
    },
    commentSave() { //点击键盘评论按钮
        let that = this
        if (that.data.commentId) { // 有commentid是二级评论
            that.replyComment()
        } else {
            that.replyArticle()
        }
    },
    clickReply(e) { // 点击评论中的回复
        let that = this
        let {
            pubuserid,
            commentid,
            pubusername
        } = e.currentTarget.dataset
        that.setData({
            pubUserId: pubuserid,
            commentId: commentid,
            commentPlachold: '@' + pubusername + '：'
        })
    },
    replyArticle() { // 直接评论文章
        if (this.data.commentValue === null || this.data.commentValue.length === 0) {
            common.showToast('您没有输入任何文字')
            return
        }
        // 不是飞羊小程序不走云函数校验
        if (!config.isFyApp) {
            this.submitArticleComment()
        }
        const that = this
        wx.cloud.callFunction({
            name: 'ContentCheck',
            data: {
                txt: that.data.commentValue
            },
            success(res) {
                if (res.result.errCode == 87014) {
                    common.showToast('文字违规，请重新输入')
                } else {
                    that.submitArticleComment()
                }
            },
            fail(err) {
                common.showToast('文字违规，请重新输入')
            }
        })
    },
    submitArticleComment() {
        const that = this
        // 合规
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            articleId: that.data.articleId,
            content: that.data.commentValue,
        }
        common.post('/storeArticle/saveStoreArticleComment', tempJson, function (res) {
            if (res.status === 200) {
                that.getCommentList()
                that.clearReplyInfo()
                common.showToast('评论成功', 'success')
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    replyComment(e) { // 回复某一条回复
        if (this.data.commentValue === null || this.data.commentValue.length === 0) {
            common.showToast('您没有输入任何文字')
            return
        }
        if (!config.isFyApp) {
            this.submitReplyComment()
        }
        const that = this
        wx.cloud.callFunction({
            name: 'ContentCheck',
            data: {
                txt: that.data.commentValue
            },
            success(res) {
                if (res.result.errCode == 87014) {
                    console.log(res.errCode)
                    common.showToast('文字违规，请重新输入')
                } else {
                    // 合规
                    that.submitReplyComment()
                }
            },
            fail(err) {
                common.showToast('文字违规，请重新输入')
            }
        })
    },
    submitReplyComment() {
        const that = this
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            pubUserId: that.data.userInfo.id,
            commentId: that.data.commentId,
            content: that.data.commentValue,
        }
        common.post("/storeArticle/saveStoreArticleCommentChat", tempJson, function (res) {
            if (res.status == 200) {
                that.getCommentList()
                that.clearReplyInfo()
                common.showToast('评论成功', 'success')
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    clearReplyInfo() {
        this.setData({
            commentValue: '',
            pubUserId: "",
            commentId: '',
            commentPlachold: '我来说几句'
        })
    },
    onShareAppMessage: function () {
        let that = this
        common.post("/storeArticle/saveStoreArticleShareNum", {
            articleId: that.data.articleId
        },
            function (res) {
                console.log(res)
            })
        return {
            title: that.data.articleDetail.title,
            path: '/pages/discovery/articleDetail/index?id=' + that.data.articleId,
            imageUrl: that.data.articleDetail.imgUrl,
        }
    },
    textareaBindblur: function () {
        this.setData({
            textareaForce: false
        })
    },
    textareaBindfocus: function () {
        this.setData({
            textareaForce: true
        })
    },
    collectAction() {
        if (!this.data.articleDetail.focusFlag) {
            this.focusStoreArticle()
        }
    },
    focusStoreArticle() {
        const that = this
        const param = {
            userId: that.data.userInfo.id ? that.data.userInfo.id : '',
            token: that.data.token ? that.data.token : '',
            articleId: that.data.articleId
        }
        common.post('/storeArticle/focusStoreArticle', param, function (res) {
            if (res.status === 200) {
                that.getArticleDetail()
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    //获取全部列表
    getAllComment() {
        wx.navigateTo({
            url: '/pages/discovery/comment/index?itemId=' + this.data.articleId,
        })
    },
})